import AMapLoader from "@amap/amap-jsapi-loader";
import { GaodeMap } from "@antv/l7";
import { HeatmapLayer, LarkMap } from "@antv/larkmap";
import { Button, Modal, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import styled from "styled-components";
import AirBarEcharts from "./components/AirBarEcharts";
import AirPieECharts from "./components/AirPieECharts";
import TimelineController from "./components/DateController";

import HumiECharts from "./components/HumiECharts";
import TempECharts from "./components/TempECharts";
import EchartsLeft from "./EchartsLeft";
import EchartsRight from "./EchartsRight";
const chartContainerStyle = {
  width: "350px",
  height: "430px",
  backgroundColor: "rgba(2, 16, 25, 0.8)",
  position: "absolute",
  padding: "20px 17px",
};
const LeftEchartsStyle = {
  width: "306px",
  height: "670px",
  backgroundColor: "rgba(2, 16, 25, 0.8)",
  top: "20px",
  left: "20px",
  zIndex: 100,
};
const RightEchartsStyle = {
  width: "306px",
  height: "670px",
  backgroundColor: "rgba(2, 16, 25, 0.8)",
  top: "20px",
  right: "20px",
  zIndex: 100,
};
const latlngStyle = {
  display: "flex",
  justifyContent: "space-between",
  position: "absolute",
  backgroundColor: "rgba(2, 16, 25, 0.8)",
  bottom: "10%",
  left: "20px",
  zIndex: 100,
  width: "306px",
  padding: "5px 20px",
  color: "#fff",
  fontSize: "14px",
};
const EchartsStyle = {
  position: "absolute",
  padding: "20px",
};
const pie = {
  display: "flex",
};
const searchBox = {
  position: "absolute",
  left: "40%",
  top: "40px",
  zIndex: 100,
};
// 添加全局样式或使用 styled-components
const CustomModalWrapper = styled.div`
  .ant-modal-content {
    box-shadow: none;
    padding: 0;
    width: 0;
  }

  .ant-modal-close {
    display: none; // 隐藏关闭按钮
  }

  .ant-modal-body {
    padding: 0;
  }
`;
const AMapHome = () => {
  const airData = useRef({});
  const [airDatajson, setAirDatajson] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [address, setAddress] = useState({
    province: "",
    city: "",
    district: "",
  });
  const [latlng, setLatlng] = useState({ lat: "", lng: "" });
  const [AMapInstance, setAMapInstance] = useState(null);
  const [map, setMap] = useState(null);
  const [searchValue, setSearchValue] = useState("");
  const [source, setSource] = useState({
    data: [],
    parser: { type: "json", x: "lng", y: "lat" },
  });

  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  useEffect(() => {
    console.log(window.innerWidth,'window.innerWidth;')
    console.log(window.innerHeight,'window.innerHeight;')
    const loadData = async () => {
      try {
        const response = await fetch("/data/airjson.json");
        const datajson = await response.json();
        var airdata = datajson.map((item) => ({
          lnglat: [item.long, item.lat],
          air: item,
        }));
        setAirDatajson(airdata);
        const slicedArr = datajson.slice(178000);

        const heatData = slicedArr.map((item) => ({
          lng: item.long,
          lat: item.lat,
          t: item.i,
          c: (Math.floor(Math.random() * 10) + 1) * 100,
        }));
     console.log(heatData,'heatData')
        const data = heatData;
        setSource((prevState) => ({ ...prevState, data }));

      } catch (error) {
        console.error("加载数据失败:", error);
      }
    };
    loadData();
  }, []);
  const ChangeSource =(data)=>{
    setSource((prevState) => ({ ...prevState, data }));
  }

  /**
   * 根据经纬度获取省、市、区信息
   * @param {Object} AMap - 高德地图实例
   * @param {Object} lnglat - 经纬度对象
   */

  function getprovinceCity(AMap, lnglat) {
    const getlnglat = [lnglat.lng, lnglat.lat];
    var geocoder = new AMap.Geocoder();
    // 根据坐标逆地理编码
    geocoder.getAddress(getlnglat, function (status, result) {
      if (status === "complete" && result.regeocode) {
        const addressComponent = result?.regeocode?.addressComponent;
        const { province, city, district } = addressComponent;
        // 设置地址信息，
        setAddress({
          province,
          city,
          district,
        });
      } else {
        console.log("获取地址失败", result);
      }
    });
  }
  // 定义一个函数来计算两点之间的欧几里得距离
  function calculateDistance(lat1, lng1, lat2, lng2) {
    return Math.sqrt(Math.pow(lat1 - lat2, 2) + Math.pow(lng1 - lng2, 2));
  }

  function findlatlng(evenlnglat, airDatajson) {
    // airDatajson十七万点数据
    let minDistance = Infinity;
    let closestData = null;

    // 遍历数据数组
    for (let i = 0; i < airDatajson.length; i++) {
      const currentData = airDatajson[i].air;
      const distance = calculateDistance(
        evenlnglat.lat,
        evenlnglat.lng,
        currentData.lat,
        currentData.long
      );

      if (distance < minDistance) {
        minDistance = distance;
        closestData = currentData;
      }
    }
    airData.current = closestData;
  }

  const handleSearch = async () => {
    if (!searchValue || !AMapInstance) {
      message.warning("请输入搜索内容");
      return;
    }
    const geocoder = new AMapInstance.Geocoder();
    try {
      const result = await new Promise((resolve, reject) => {
        geocoder.getLocation(searchValue, (status, result) => {
          status === "complete"
            ? resolve(result)
            : reject(new Error("地址解析失败"));
        });
      });
      const { location } = result.geocodes[0];
      map.setCenter([location.lng, location.lat]);
      map.setZoom(8);
      var marker = new AMapInstance.Marker({
        position: [location.lng, location.lat], // 标记位置
        map: map, // 将标记添加到地图上
      });
      map.add(marker);
      marker.on("click", function (e) {
        const { lnglat } = e;
        setLatlng({
          lat: lnglat.lat,
          lng: lnglat.lng,
        });
        getprovinceCity(AMapInstance, lnglat);
        // findlatlng(lnglat, airDatajson);
        showModal();
      });
    } catch (error) {
      message.error("搜索失败", error);
    }
  };

  const getMapInstance = () => {
    return AMapLoader.load({
      key: "cd6ee207dbb4b3d02a61760224976ed9",
      version: "2.0", 
      plugins: ["AMap.Geocoder", "AMap.HeatMap",],
    }).then((AMap) => {
      const map = new AMap.Map("container", {
        zoom: 16, //初始化地图层级
        center: [116.397428, 39.90923], //初始化地图中心点
        mapStyle: "amap://styles/darkblue",
      });
      setMap(map);
      setAMapInstance(AMap);
      return new GaodeMap({
        mapInstance: map,
      });
    });
  };

  function clickHandler(e) {
    const { lnglat } = e;
    setLatlng({
      lat: lnglat.lat,
      lng: lnglat.lng,
    });
    findlatlng(lnglat, airDatajson);
    showModal();
    getprovinceCity(AMapInstance, lnglat);
  }

  const layerOptions = {
    autoFit: true,
    shape: "heatmap",
    size: 5,
    style: {
      intensity: 3,
      // radius: 10,
      opacity: 1,
      rampColors: {
        colors: [
          // "#FF4818",
          // "#F7B74A",
          // "#FFF598",
          // "#F27DEB",
          // "#8C1EB2",
          // "#421EB2",

          '#206C7C',
          '#2EA9A1',
          '#91EABC',
          '#FFF598',
          '#F7B74A', 
          '#FF4818',
        ],
        positions: [0, 0.2, 0.4, 0.6, 0.8, 1.0],
      },
    },
  };

 
  return (
    <>
      <LarkMap
        id="container"
        map={getMapInstance}
        style={{ height: '900px' }}
        onClick={clickHandler}
      >
        <HeatmapLayer {...layerOptions} source={source} />
        <div style={searchBox}>
          <input
            style={{
              backgroundColor: " #003366",
              padding: "5px",
              borderRadius: "8px",
              width: "300px",
              zIndex: 1000,
              margin: "0 auto",
            }}
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            placeholder="请输入地点名称或经纬度"
            className="search-input"
          />
          <Button onClick={handleSearch}>搜索</Button>
        </div>
        <Modal
          open={isModalOpen}
          footer={null}
          onCancel={handleCancel}
          wrapClassName="custom-modal"
          style={{
            padding: 0,
            backgroundColor: "transparent",
          }}
          modalRender={(node) => (
            <CustomModalWrapper>{node}</CustomModalWrapper>
          )}
        >
          <div style={chartContainerStyle}>
            <div
              style={{
                color: "#FFF",
                width: "300px",
              }}
            >
              {address.province}
              {address.city}
              {address.district}
            </div>
            <div style={pie}>
              <AirPieECharts airData={airData.current} />

              <TempECharts temp={airData.current.temp} />
              <HumiECharts humi={airData.current.humi} />
            </div>
            <div>
              <AirBarEcharts airData={airData.current} />
            </div>
          </div>
        </Modal>
        <div style={{ ...LeftEchartsStyle, ...EchartsStyle }}>
          <EchartsLeft airData={airData.current} />
        </div>
        <div style={{ ...RightEchartsStyle, ...EchartsStyle }}>
          <EchartsRight airData={airData.current} />
        </div>
        <div style={latlngStyle}>
          <div>纬度:{latlng.lat || 39.90923}</div>
          <div>经度:{latlng.lng || 116.397428}</div>
        </div>
        <TimelineController ChangeSource={ChangeSource} />
      </LarkMap>
    </>
  );
};

export default AMapHome;
